package utils

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"math/rand"
	"os"
	"reflect"
	"strings"
	"time"
)

//检查md5明文和密文是否一致
func Md5Check(content,encrypted string) bool{
	return strings.EqualFold(Md5Encode(content), encrypted)
}

//对字符串进行md5加密
func Md5Encode(data string) string{
	h := md5.New()
	h.Write([]byte(data))
	return hex.EncodeToString(h.Sum(nil))
}

//interface转Slice
func ToSlice(arr interface{}) []interface{} {
	v := reflect.ValueOf(arr)
	if v.Kind() != reflect.Slice {
		panic("toslice arr not slice")
	}
	l := v.Len()
	ret := make([]interface{}, l)
	for i := 0; i < l; i++ {
		ret[i] = v.Index(i).Interface()
	}
	return ret
}

//对字符串切片去除空值
func TrimSlice(values []string) (ret []string){
	for _,v := range values{
		if v != ""{
			ret = append(ret, v)
		}
	}
	return
}

func PrintPretty(v interface{}, mark string) (err error) {
	fmt.Printf("*********%s\n", mark)
	data, err := json.MarshalIndent(v, "", "  ")
	if err != nil {
		return
	}
	data = append(data, '\n')
	os.Stdout.Write(data)
	return
}

//随机生成字符串
func  GetRandomString(l int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

//去除string切片中重复的值
func RemoveDuplicateElement(addrs []string) []string {
	result := make([]string, 0, len(addrs))
	temp := map[string]struct{}{}
	for _, item := range addrs {
		if _, ok := temp[item]; !ok {
			temp[item] = struct{}{}
			result = append(result, item)
		}
	}
	return result
}

//获取某个字符串是否存在数组中的次数，0表示没有
func Contains(array interface{}, val interface{}) (index int) {
	index = 0
	switch reflect.TypeOf(array).Kind() {
	case reflect.Slice: {
		s := reflect.ValueOf(array)
		for i := 0; i < s.Len(); i++ {
			if reflect.DeepEqual(val, s.Index(i).Interface()) {
				index = i + 1
				return
			}
		}
	}
	}
	return
}

//根据时间戳获取时间
func GetDateByTime(cateTime int64) string {
	return time.Unix(cateTime,0).Format("2006-01-02 15:04:05")
}



